package com.example.fw;


import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.selenesedriver.FindElement;


import com.example.tests.SortedListOf;

public class AccountHelper extends WebDriverHelperBase {

	public AccountHelper(ApplicationManager manager) {
		super(manager);
	}
	
	public void signup(User user) {
		openUrl("/");
		click(By.cssSelector("span.bracket-link"));
		type(By.name("username"), user.login);
		type(By.name("email"), user.email);
		click(By.cssSelector("input.button"));
		
		WebElement errorMessage = findElement(By.cssSelector("table.width50 tbody tr td p"));
		if(errorMessage != null){
			throw new RuntimeException(errorMessage.getText());
		}
		
		pause(3000);
		String msg = manager.getMailHelper().getNewMail(user.login, user.password);
		System.out.println(msg);
		String confirmationLink = getConfirmationLink(msg);
		openAbsoluteUrl(confirmationLink);
		
		type(By.name("password"), user.password);
		type(By.name("password1"), user.password);
		click(By.cssSelector("input.button"));		
	}

	public String getConfirmationLink(String text){
		Pattern regex = Pattern.compile("http\\S*");
		Matcher matcher = regex.matcher(text);
		if(matcher.find()){
			return matcher.group();
		} else {
			return "";
		}
	}
	
	public void login(User user) {
		openUrl("/");
		type(By.name("username"), user.login);
		type(By.name("password"), user.password);
		click(By.cssSelector("input.button"));	
	}

	public String loggedUser(User user) {
		WebElement element = findElement(By.cssSelector("td.login-info-left span"));
		return element.getText();
	}

	public AccountHelper deleteUser(User user) {
		if(findElement(By.linkText(user.login)).isDisplayed()){
			click(By.linkText(user.login));
			click(By.xpath("//form[2]/input[3]"));
			click(By.xpath("//form/input[4]"));
			pause(5000);
		} else{
			throw new RuntimeException("The table is not a user = " + user.login);
		}
		return this;
	}

	public AccountHelper loginAdministrator(User admin) {
		openUrl("/");
		type(By.name("username"), admin.login);
		type(By.name("password"), admin.password);
		click(By.cssSelector("input.button"));
		return this;
	}
	
	public AccountHelper gotoUserManagePage() {
		click(By.linkText("Manage"));
		click(By.linkText("Manage Users"));
		return this;
	}

	public SortedListOf<User> getList() {
		SortedListOf<User> user = new SortedListOf<User>();
		List <WebElement> elements = driver.findElements(By.xpath("//table[3]/tbody/tr")); 
		for (WebElement element : elements) {
			if(!element.findElement(By.xpath("td[1]")).getText().contains("Manage Accounts") || ! element.findElement(By.xpath("td[1]")).getText().equals("User name")){
			    user.add(new User().setLogin(element.findElement(By.xpath("td[1]")).getText()));
			}
		}
		return user;
	};
}
